package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.annotation.RequiresPermissionsDesc;
import com.qf.pojo.DtsRole;
import com.qf.service.PermsService;
import com.qf.service.RoleService;
import com.qf.util.JacksonUtil;
import com.qf.util.Permission;
import com.qf.util.PermissionUtil;
import com.qf.util.ResponseUtil;
import com.qf.vo.CatVo;
import com.qf.vo.PermVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @auther Administrator
 * @date 2023/2/22 16:29
 */
@RequestMapping("/admin/role")
@RestController
@CrossOrigin
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermsService permsService;
    @Autowired //拿到整个Spring容器
    private ApplicationContext applicationContext;
    /**
     * - 接口地址 : http://localhost:8083/admin/role/options
     * - GET请求
     * - 下行数据 :
     */
    @GetMapping("/options")
            public Object options(){
                List<DtsRole> roleList = roleService.findRoleList();

                //Vo :
                List<CatVo> catVoList = roleList.stream().map(dtsRole -> {
                    CatVo vo = new CatVo();
                    vo.setValue(dtsRole.getId());
            vo.setLabel(dtsRole.getName());
            return vo;
        }).collect(Collectors.toList());
        return ResponseUtil.ok(catVoList);
    }
    /**
     * http://localhost:8080/admin/role/list?page=1&limit=20&sort=add_time&order=desc&rolename=111
     * 分页查询
     */
    @RequiresPermissions(value = {"admin:role:list"})
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "查询")
    @GetMapping("/list")
    public Object list(
            String rolename,
            String sort,
            String order,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer limit
    ){
        IPage<DtsRole> ipage = roleService.findRolePageByQuery(rolename,sort,order,page,limit);
        Map data = new HashMap<>();
        data.put("total",ipage.getTotal());
        data.put("items",ipage.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * /create
     */
    @RequiresPermissions(value = "admin:role:create")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody DtsRole dtsRole){
        dtsRole = roleService.create(dtsRole);
        return ResponseUtil.ok(dtsRole);
    }
    /**
     * update
     */
    @RequiresPermissions(value = "admin:role:update")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody DtsRole dtsRole){
        dtsRole = roleService.update(dtsRole);
        return ResponseUtil.ok(dtsRole);
    }

    /**
     * delete
     */
    @RequiresPermissions(value = "admin:role:delete")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsRole dtsRole){
        dtsRole = roleService.delete(dtsRole);
        return ResponseUtil.ok(dtsRole);
    }


    /**
     * 授权
     *
     * 接口地址 : http://localhost:8083/admin/role/permissions?roleId=5
     */
    @GetMapping("/permissions")

    public Object permissions(Integer roleId){
        String basePackage = "com.qf.controller";
        List<Permission> permissions = PermissionUtil.listPermission(applicationContext,basePackage);
        //1:父子孙三代的菜单集合
        List<PermVo> systemPermissions = PermissionUtil.listPermVo(permissions);
        //2:后端权限集合
        Integer[] roleIds = {roleId};
        //从Mysql数据库查询的原数据
        Set<String> assignedPermissions = permsService.findPermsByRoleIds(roleIds);
        //2.1:可能是*
        //2.2:可能是空  不用解决
        //2.3: 可能有相同也可以没有相同 也不用解决

        //处理后的数据
        assignedPermissions = handlerPerms(assignedPermissions,basePackage);

        //返回数据
        Map data = new HashMap();
        data.put("systemPermissions",systemPermissions);
        data.put("assignedPermissions",assignedPermissions);
        return ResponseUtil.ok(data);
    }

    //处理查询到权限
    private Set<String> handlerPerms(Set<String> assignedPermissions,String basePackage) {
        //1:判断是不是null
    /*    if(CollectionUtils.isEmpty(assignedPermissions)){
            return new HashSet<>();
        }*/
        Optional.ofNullable(assignedPermissions).orElse(new HashSet<>());
        //2:判断是不是*
        if(assignedPermissions.contains("*")){
            //超级管理员
            List<Permission> permissionList = PermissionUtil.listPermission(applicationContext, basePackage);
            return permissionList.stream().map(permission ->
                    permission.getRequiresPermissions().value()[0]
            ).collect(Collectors.toSet());
        }else{
            //不是超级管理员
            return assignedPermissions;
        }


    }
    /**
     * 授权操作
     *{
     * 	"permissions": [
     * 		"admin:category:update",
     * 		"admin:category:list",
     * 		"admin:category:read",
     * 		"admin:category:delete",
     * 		"admin:category:create",
     * 		"admin:role:permission:update",
     * 		"admin:role:update",
     * 		"admin:role:list",
     * 		"admin:role:read",
     * 		"admin:role:delete",
     * 		"admin:role:permission:get",
     * 		"admin:role:create"
     * 	],
     * 	"roleId": 31
     * }
     */
    //@RequiresPermissions()

    @PostMapping("/permissions")
    public Object permissions(@RequestBody String body){

        //角色ID
        Integer roleId = JacksonUtil.parseInteger(body, "roleId");
        //权限集合
        List<String> permissionList = JacksonUtil.parseStringList(body, "permissions");
        //授权操作
        permsService.updatePermListByRoleId(roleId,permissionList);

        return ResponseUtil.ok();

    }
}


